import { createI18n } from 'vue-i18n'
import zhHans from './locale/zh-Hans'
import zhHant from './locale/zh-Hant'
import pt from './locale/pt'

const i18n = createI18n({
  legacy: false,
  globalInjection: true,
  locale: uni.getStorageSync('language') || 'zh-Hans',
  fallbackLocale: 'zh-Hans',
  messages: {
    'zh-Hans': zhHans,
    'zh-Hant': zhHant,
    'pt': pt
  },
  missing: (locale, key) => {
    console.warn(`[i18n] Missing translation key: "${key}" for locale: "${locale}"`)
    return key
  },
  fallbackWarn: false,
  missingWarn: process.env.NODE_ENV === 'development'
})

export function setLanguage(locale) {
  i18n.global.locale.value = locale
  uni.setStorageSync('language', locale)
  
  const tabBarTexts = [
    i18n.global.t('tabbar.home'),
    i18n.global.t('tabbar.appointment'),
    i18n.global.t('tabbar.my')
  ]
  
  tabBarTexts.forEach((text, index) => {
    uni.setTabBarItem({
      index,
      text
    })
  })
  
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  if (currentPage?.route) {
    const titleKey = currentPage.$page?.navigationBarTitleText
    if (titleKey) {
      uni.setNavigationBarTitle({
        title: i18n.global.t(titleKey)
      })
    }
  }
}

export default i18n 